package com.bocai.dahuatech.ui.activity;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.PromotionProductBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseActivity;
import com.bocai.dahuatech.event.MainEvent;
import com.bocai.dahuatech.ui.adapter.FlowAdapter;
import com.bocai.dahuatech.ui.adapter.PromotionProductListAdapterHolder;
import com.bocai.dahuatech.ui.view.LoadMoreRecyclerView;
import com.bocai.dahuatech.utils.AESUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 促销产品（产品列表）
 */
public class PromotionProductActivity extends BaseActivity {
    @Bind(R.id.swipe_product_third)
    SwipeRefreshLayout swipeProduct;
    @Bind(R.id.lv_product_third)
    LoadMoreRecyclerView lvProductThird;
    @Bind(R.id.tv_product_count)
    TextView tvCount;
    @Bind(R.id.ll_title_right)
    LinearLayout llTitle;
    @Bind(R.id.et_search)
    EditText etSearch;
    PromotionProductBean bean;
    FlowAdapter adapter;
    PromotionProductListAdapterHolder productAdapter;
    int pager=1;
    String what;
    List<PromotionProductBean.ContentEntity> datas=new ArrayList<>();
    @Override
    protected int contentView() {
        return R.layout.activity_promotion_product;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        what=getIntent().getStringExtra("what");
        initToolbar(R.string.promotionproduct);
        llTitle.setVisibility(View.GONE);
        etSearch.setHint(R.string.productserchhint);
        lvProductThird.setLayoutManager(new LinearLayoutManager(this));
        getDatas();
        initEvent();
    }

    /**
     * 捕捉back
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if("promotion".equals(what)){

                startActivity(new Intent(PromotionProductActivity.this,HomeActivity.class));
                finish();
            }else{
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void initEvent()
    {
        super.initEvent();
        mToolbar.setNavigationOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if("promotion".equals(what))
                {
                    startActivity(new Intent(PromotionProductActivity.this, HomeActivity.class));
                    finish();
                }else
                {
                    finish();
                }
            }
        });
        swipeProduct.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
        {
            @Override
            public void onRefresh()
            {
                pager = 1;
                datas.clear();
                getDatas();
            }
        });
        lvProductThird.setLoadMoreListener(new LoadMoreRecyclerView.LoadMoreListener()
        {
            @Override
            public void onLoadMore() {
                pager++;
                getDatas();
            }
        });

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener()
        {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
            {
                if (actionId == EditorInfo.IME_ACTION_SEARCH)
                {
                    pager=1;
                    datas.clear();
                    getDatas();
                }
                return false;
            }
        });

    }

    @Override
    public void onEventMainThread(MainEvent event)
    {
        super.onEventMainThread(event);
        if(event.msg.equals("goshopcart"))
        {
            finish();
        }
    }
    private void getDatas() {
        showLoading();
        getTestApi().getPromotionProductList(etSearch.getText().toString(),pager,20)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
    Observer<BaseBean> observer=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            hideLoading();
            showToast(R.string.neterror);
            swipeProduct.setRefreshing(false);
            Log.e("error",e.toString());
        }

        @Override
        public void onNext(BaseBean baseBean) {
            hideLoading();
            swipeProduct.setRefreshing(false);
            if(baseBean.getReturnNo().equals("1")) {
                String result = AESUtils.decode(baseBean.getContent());
                result = start + result + end;
                Log.e("result", result);

                bean = new Gson().fromJson(result, PromotionProductBean.class);
                datas.addAll(bean.getContent());
                tvCount.setText(baseBean.getReturnInfo() + getResources().getString(R.string.datacount));
                if(pager==1){
                    if(bean.getContent().size()==0){
                        showToast(R.string.noserchproduct);
                    }
                    productAdapter = new PromotionProductListAdapterHolder(PromotionProductActivity.this, bean.getContent());
                    lvProductThird.setAdapter(productAdapter);
                }else
                {
                    productAdapter.addDatas(bean.getContent());
                }
                if(bean.getContent().size()<20){
                    lvProductThird.notifyMoreFinish(false);
                }else{
                    lvProductThird.notifyMoreFinish(true);
                }
                productAdapter.SetOnItemClickListener(new PromotionProductListAdapterHolder.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Intent intent = new Intent(PromotionProductActivity.this, NewProductDetailActivity.class);
                        intent.putExtra("productId", datas.get(position).getFID());
                        intent.putExtra("solutionId", "0");
                        if("promotion".equals(what)){
                            intent.putExtra("what",1);
                        }
                        startActivity(intent);
                    }
                });

            }else{
                showToast(baseBean.getReturnInfo());
            }

        }
    };

}
